<?php
set_time_limit(0);
/**
 * 把省市四级联动 生成JSON格式的内容并保存到文件中。注意此脚本不要在WEB服务器下执行，在系统控制台中用php.exe去执行。命令：php.exe create_json.php 注意配置PHP的PATH环境
 */
$pdo = new PDO('mysql:host=localhost;dbname=city_4j_202007;port=3306','root','root');
function to_json($code,$name=''){
	global $pdo;
	$arr = [];
	if(empty($code)){
		$sql = "SELECT code,pid,name FROM area_table WHERE pid=0 AND sort=1";// AND code like '43%'
	}else{
		$sql = "SELECT code,pid,name FROM area_table WHERE pid={$code}";// AND code like '43%'
	}
	$stmt = $pdo->query($sql);
	$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
	foreach($result as $v){
		//echo $v['name'];//得到中文名,有三列code,pid,name
		$sql = "SELECT code,pid,name FROM area_table WHERE pid={$v['code']}"; // AND code like '43%'
		$stmt1 = $pdo->query($sql);
		$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
		if($result1){
			//return $temp[$v['name']] = to_json($v['name'])
			//to_json($v['code']);
			//array_push($arr,$v['name']);
			$arr[$v['name']] = to_json($v['code'],$v['name']);
		}else{
			//array_push($arr,$v['name']);
			//array_push($arr[$name],$v['name']);
			$arr[] = $v['name'];
		}
	}
	return $arr;
	//print_r($arr);
	
	
	//var_dump($result);
}
//把生成的数组保存为JSON格式
file_put_contents('js/city.json', json_encode(to_json(''),JSON_UNESCAPED_UNICODE));

?>